package com.hankol.message.imConfig

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.text.Spannable
import android.text.SpannableString
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.LinearLayout.LayoutParams
import androidx.core.content.ContextCompat
import androidx.core.text.TextUtilsCompat
import com.baselibrary.bean.IMUserBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.utils.GsonUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.TimeUtil
import com.hankol.message.R
import io.rong.imkit.R.string
import io.rong.imkit.conversation.messgelist.provider.BaseMessageItemProvider
import io.rong.imkit.manager.AudioRecordManager
import io.rong.imkit.model.UiMessage
import io.rong.imkit.userinfo.RongUserInfoManager
import io.rong.imkit.widget.adapter.IViewProviderListener
import io.rong.imkit.widget.adapter.ViewHolder
import io.rong.imlib.common.NetUtils
import io.rong.imlib.model.MessageContent
import io.rong.imlib.model.Message.MessageDirection
import io.rong.message.HQVoiceMessage
import java.util.Locale

//为了给头像加上vip标签，需要替换掉内置的模版
class CustomHQVoiceMessageItemProvider : BaseMessageItemProvider<HQVoiceMessage>() {
    init {
        this.mConfig.showReadState = true
        this.mConfig.showContentBubble = false
    }

    override fun onCreateMessageContentViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_hq_voice_message, parent, false)
        return ViewHolder(parent.context, view)
    }

    override fun bindMessageContentViewHolder(holder: ViewHolder, parentHolder: ViewHolder, message: HQVoiceMessage, uiMessage: UiMessage, position: Int, list: List<UiMessage>, listener: IViewProviderListener<UiMessage>) {
        val isSender = uiMessage.message.messageDirection == MessageDirection.SEND
        holder.setBackgroundRes(R.id.rc_voice_bg, if (isSender) R.drawable.rc_ic_bubble_right else R.drawable.rc_ic_bubble_left)
        var minWidth = 70
        var maxWidth = 204
        val scale = holder.context.resources.displayMetrics.density
        minWidth = (minWidth.toFloat() * scale + 0.5f).toInt()
        maxWidth = (maxWidth.toFloat() * scale + 0.5f).toInt()
        val duration = AudioRecordManager.getInstance().maxVoiceDuration
        holder.getView<View>(R.id.rc_voice_bg).layoutParams.width = minWidth + (maxWidth - minWidth) / duration * message.duration
        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == 1) {
            holder.setText(R.id.rc_duration, String.format("\"%s", message.duration))
        } else {
            holder.setText(R.id.rc_duration, String.format("%s\"", message.duration))
        }

        val animationDrawable: AnimationDrawable?
        val lp: LayoutParams
        if (uiMessage.message.messageDirection == MessageDirection.SEND) {
            holder.setTextColor(R.id.rc_duration, ContextCompat.getColor(holder.context, R.color.white))
            animationDrawable = holder.context.resources.getDrawable(R.drawable.rc_an_voice_send) as AnimationDrawable
            holder.setVisible(R.id.rc_voice, false)
            holder.setVisible(R.id.rc_voice_send, true)
            (holder.getView<View>(R.id.rc_duration) as TextView).gravity = 8388629
            lp = holder.getView<View>(R.id.rc_duration).layoutParams as LayoutParams
            lp.marginEnd = 12
            holder.getView<View>(R.id.rc_duration).layoutParams = lp
            if (uiMessage.isPlaying) {
                holder.setImageDrawable(R.id.rc_voice_send, animationDrawable)
                animationDrawable?.start()
            } else {
                holder.setImageResource(R.id.rc_voice_send, R.drawable.rc_voice_send_play3)
            }

            holder.setVisible(R.id.rc_voice_unread, false)
            holder.setVisible(R.id.rc_voice_download_error, false)
            holder.setVisible(R.id.rc_download_progress, false)
        } else {
            animationDrawable = holder.context.resources.getDrawable(R.drawable.rc_an_voice_receive) as AnimationDrawable
            holder.setVisible(R.id.rc_voice, true)
            holder.setVisible(R.id.rc_voice_send, false)
            (holder.getView<View>(R.id.rc_duration) as TextView).gravity = 8388627
            lp = holder.getView<View>(R.id.rc_duration).layoutParams as LayoutParams
            lp.marginStart = 12
            holder.getView<View>(R.id.rc_duration).layoutParams = lp
            if (uiMessage.isPlaying) {
                holder.setImageDrawable(R.id.rc_voice, animationDrawable)
                animationDrawable?.start()
            } else {
                holder.setImageResource(R.id.rc_voice, R.drawable.rc_voice_receive_play3)
            }

            if (message.localPath != null) {
                holder.setVisible(R.id.rc_voice_download_error, false)
                holder.setVisible(R.id.rc_download_progress, false)
                holder.setVisible(R.id.rc_voice_unread, !uiMessage.message.receivedStatus.isListened)
            } else if (uiMessage.state != 1 && NetUtils.isNetWorkAvailable(holder.context)) {
                if (uiMessage.state == 2) {
                    holder.setVisible(R.id.rc_voice_unread, false)
                    holder.setVisible(R.id.rc_voice_download_error, false)
                    holder.setVisible(R.id.rc_download_progress, true)
                } else {
                    holder.setVisible(R.id.rc_voice_unread, true)
                    holder.setVisible(R.id.rc_voice_download_error, false)
                    holder.setVisible(R.id.rc_download_progress, false)
                }
            } else {
                holder.setVisible(R.id.rc_voice_unread, false)
                holder.setVisible(R.id.rc_voice_download_error, true)
                holder.setVisible(R.id.rc_download_progress, false)
            }
        }

    }

    override fun onItemClick(holder: ViewHolder, message: HQVoiceMessage, uiMessage: UiMessage, position: Int, list: List<UiMessage>, listener: IViewProviderListener<UiMessage>?): Boolean {
        if (listener != null) {
            listener.onViewClick(-7, uiMessage)
            return true
        } else {
            return false
        }
    }

    override fun isMessageViewType(messageContent: MessageContent): Boolean {
        return messageContent is HQVoiceMessage && !messageContent.isDestruct()
    }

    override fun getSummarySpannable(context: Context, hqVoiceMessage: HQVoiceMessage): Spannable {
        return SpannableString(context.getString(string.rc_conversation_summary_content_voice))
    }

    override fun bindViewHolder(holder: ViewHolder, uiMessage: UiMessage, position: Int, list: MutableList<UiMessage>, listener: IViewProviderListener<UiMessage>) {
        super.bindViewHolder(holder, uiMessage, position, list, listener)
        holder.setText(R.id.rc_time, TimeUtil.fromToday(uiMessage.sentTime))
        if (uiMessage.senderUserId.checkNotNull() && RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).checkNotNull() && RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).extra.checkNotNull()) {
            val isFans = GsonUtils.parseJsonToBean(RongUserInfoManager.getInstance().getUserInfo(uiMessage.senderUserId).extra, IMUserBean::class.java).isFans == 1
            holder.setVisible(R.id.img_vip_tag_right, ("${SpUtils.getInstance().loadUserBean.data.id}").equals(uiMessage.senderUserId) && isFans)
            holder.setVisible(R.id.img_vip_tag_left, (!("${SpUtils.getInstance().loadUserBean.data.id}").equals(uiMessage.senderUserId)) && isFans)
        }
    }
}
